package com.zemb.flxwear.UI.Fragment;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.zemb.flxwear.Bean.ReportItem;
import com.zemb.flxwear.DB.DataBaseHelper;
import com.zemb.flxwear.R;
import com.zemb.flxwear.UI.CustomView.CircularSwitch;
import com.zemb.flxwear.Utils.ByteUtils;
import com.zemb.flxwear.Utils.DeviceUtils;
import com.zemb.flxwear.Utils.LogUtils;
import com.zemb.flxwear.Utils.VoicePlayUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

public class BloodPressureFragment extends BaseFragment implements View.OnClickListener {

    private TextView tv_hp_value, tv_lp_value, tv_pulse_value, tv_device_name;
    private Button btn_measure;
    private CircularSwitch circularSwitch;
    private DataBaseHelper.BloodPressure bloodPressure;


    @Override
    int getLoadingPageId() {
        return R.id.loading_page;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_blood_pressure;
    }

    @Override
    void onNotifyCallBack(byte[] data) {
        try {


            LogUtils.PrintLog(data.toString()
            );
            if (data.length < 3) {
                return;
            }
            switch (data[2]) {
                case (byte) 0xFD:
                    switch (data[3]) {
                        /**
                         * 0x10	启动应答
                         * 0x01	人体心跳信号太小或压力突降
                         * 0x02	杂讯干扰
                         * 0x03	充气时间过长
                         * 0x04	测得的结果异常
                         * 0X05	保留
                         * 0X06	腕带没有缠绕好
                         * 0x07	加压异常
                         * 0x08	保留
                         * 0x09	保留
                         * 0x0A	保留
                         * 0x0B	电源低电压
                         * 0x0C	校正异常
                         * 0X0D	保留
                         * 0x0E	血压计异常
                         * 0x0F	保留
                         * 0x20	校准成功
                         */
                        case (byte) 0x10:
                            Log.d("BloodPressureFragment", "启动应答");
//                        btn_measure.setText("启动应答");
                            btn_measure.setText(getString(R.string.start_response));
                            break;
                        case (byte) 0x01:
                            Log.d("BloodPressureFragment", "人体心跳信号太小或压力突降");
                            //btn_measure.setText("人体心跳信号太小或压力突降");
                            btn_measure.setText(getString(R.string.heart_rate_too_small));
                            break;
                        case (byte) 0x02:
                            Log.d("BloodPressureFragment", "杂讯干扰");
//                        btn_measure.setText("杂讯干扰");
                            btn_measure.setText(getString(R.string.noise_interference));
                            break;
                        case (byte) 0x03:
                            Log.d("BloodPressureFragment", "充气时间过长");
//                        btn_measure.setText("充气时间过长");
                            btn_measure.setText(getString(R.string.inflation_time_too_long));
                            break;
                        case (byte) 0x04:
                            Log.d("BloodPressureFragment", "测得的结果异常");
//                        btn_measure.setText("测得的结果异常");
                            btn_measure.setText(getString(R.string.abnormal_result));
                            onMeasureFailed();
                            break;
                        case (byte) 0x05:
                            Log.d("BloodPressureFragment", "保留");
                            break;
                        case (byte) 0x06:
                            Log.d("BloodPressureFragment", "腕带没有缠绕好");
//                        btn_measure.setText("腕带没有缠绕好");
                            btn_measure.setText(getString(R.string.wristband_not_wound));
                            onMeasureFailed();
                            break;
                        case (byte) 0x07:
                            Log.d("BloodPressureFragment", "加压异常");
//                        btn_measure.setText("加压异常");
                            btn_measure.setText(getString(R.string.pressure_abnormality));
                            onMeasureFailed();
                            break;
                        case (byte) 0x08:
                            Log.d("BloodPressureFragment", "保留");
                            break;
                        case (byte) 0x09:
                            Log.d("BloodPressureFragment", "保留");
                            break;
                        case (byte) 0x0A:
                            Log.d("BloodPressureFragment", "保留");
                            break;
                        case (byte) 0x0B:
                            Log.d("BloodPressureFragment", "电源低电压");
//                        btn_measure.setText("电源低电压");
                            btn_measure.setText(getString(R.string.low_voltage));
                            break;
                        case (byte) 0x0C:
                            Log.d("BloodPressureFragment", "校正异常");
//                        btn_measure.setText("校正异常");
                            btn_measure.setText(getString(R.string.calibration_abnormal));
                            break;
                        case (byte) 0x0D:
                            Log.d("BloodPressureFragment", "保留");
                            break;
                        case (byte) 0x0E:
                            Log.d("BloodPressureFragment", "血压计异常");
//                        btn_measure.setText("血压计异常");
                            btn_measure.setText(getString(R.string.sphygmomanometer_abnormal));
                            onMeasureFailed();
                            break;
                        case (byte) 0x0F:
                            Log.d("BloodPressureFragment", "保留");
                            break;
                        case (byte) 0x20:
                            Log.d("BloodPressureFragment", "校准成功");
//                        btn_measure.setText("校准成功");
                            btn_measure.setText(getString(R.string.calibration_success));
                            break;
                    }
                    break;
                /**
                 * 0XFB：袖带压力
                 * 0xF2：脉搏波值
                 * 0XF3：校准压力值
                 */
                case (byte) 0xFB:
                    onMeasureStart();
                    int pressure = ByteUtils.hexToInt(data[3], data[4]);
                    Log.d("BloodPressureFragment", "袖带压力：" + pressure);
                    btn_measure.setText("" + pressure);
                    break;
                case (byte) 0xF2:
                    int pulse = ByteUtils.hexToInt(data[3], data[4]);
                    Log.d("BloodPressureFragment", "脉搏波值：" + pulse);
                    tv_pulse_value.setText("" + pulse);
                    break;
                case (byte) 0xF3:
                    int calibrate = ByteUtils.hexToInt(data[3], data[4]);
                    Log.d("BloodPressureFragment", "校准压力值：" + calibrate);
                    break;
                /**
                 包头（两个字节）	数据属性	数据位	数据位	数据位	数据位	结束字
                 0xFD 0xFD	0XFC	保留位	高压	低压	心率	0x0D 0X0A
                 **/
                case (byte) 0xFC:
                    if (!isSuccessful) {
                        isSuccessful = true;
                        bloodPressure.highPressure = Integer.parseInt(Integer.toHexString(data[3] & 0xFF), 16);
                        bloodPressure.lowPressure = Integer.parseInt(Integer.toHexString(data[4] & 0xFF), 16);
                        bloodPressure.plus = Integer.parseInt(Integer.toHexString(data[5] & 0xFF), 16);
                        bloodPressure.date = getCurrentTime();
                        onMeasureComplete();
                    } else {
                        return;
                    }
                    break;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void initData() {
        bloodPressure = new DataBaseHelper.BloodPressure();
    }


    @Override
    protected void initView(View root) {
        tv_hp_value = root.findViewById(R.id.tv_hp_value);
        tv_lp_value = root.findViewById(R.id.tv_lp_value);
        tv_pulse_value = root.findViewById(R.id.tv_pulse_value);
        tv_device_name = root.findViewById(R.id.tv_device_name);
        btn_measure = root.findViewById(R.id.btn_measure);
        circularSwitch = root.findViewById(R.id.sw_static_blood_pressure);
        circularSwitch.setOnClickListener(this);
        if (activity.getCurrentDevice() != null) {
            tv_device_name.setText(activity.getCurrentDevice().getName());
        } else {
            tv_device_name.setText(getString(R.string.click_connect_device));
        }
        root.findViewById(R.id.v_top_panel).setOnClickListener(this);
        btn_measure.setOnClickListener(this);

        tv_hp_value.setText("-");
        tv_lp_value.setText("-");
        tv_pulse_value.setText("-");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.v_top_panel:
                activity.switchFragment(DeviceUtils.UIType.CONNECT);
                break;
            case R.id.btn_measure:
                if (activity.getCurrentDevice() == null) {
                    activity.switchFragment(DeviceUtils.UIType.CONNECT);
                } else {
                }
                break;
            case R.id.sw_static_blood_pressure:
                if (circularSwitch.getSwitch()) {
                    activity.sendDeviceData(DeviceUtils.OPEN_STATIC_PRESS, service_uuid, characteristic_uuid, new BleWriteCallback() {
                        @Override
                        public void onWriteSuccess(int current, int total, byte[] justWrite) {
                            Toast.makeText(activity, getString(R.string.open_static_blood_pressure_success), Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onWriteFailure(BleException exception) {
                            Toast.makeText(activity, getString(R.string.open_static_blood_pressure_success), Toast.LENGTH_SHORT).show();

                        }
                    });
                } else {
                    activity.sendDeviceData(DeviceUtils.CLOSE_STATIC_PRESS, service_uuid, characteristic_uuid, new BleWriteCallback() {
                        @Override
                        public void onWriteSuccess(int current, int total, byte[] justWrite) {
                            Toast.makeText(activity, getString(R.string.close_static_blood_pressure_success), Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onWriteFailure(BleException exception) {
                            Toast.makeText(activity, getString(R.string.close_static_blood_pressure_fail), Toast.LENGTH_SHORT).show();
                        }
                    });
                }

        }
    }

    @Override
    public void onStartConnectDevice() {
        VoicePlayUtils.getInstance().PlayConnectStart(activity.getMeasureTag());
        showLoading(getString(R.string.connecting));
    }


    @Override
    public void onDeviceConnect(BleDevice bleDevice) {
        VoicePlayUtils.getInstance().PlayConnectSuccess(activity.getMeasureTag());
        hideLoading();
        tv_device_name.setText(bleDevice.getName());
        btn_measure.setText(getResources().getText(R.string.bluetooth_connect));
        openNotify();

    }

    @Override
    public void onDeviceConnectFail(BleDevice bleDevice, BleException exception) {
        VoicePlayUtils.getInstance().PlayConnectFailed(activity.getMeasureTag());
        hideLoading();

    }

    @Override
    public void onDeviceDisConnected(BleDevice bleDevice) {
        try {
            if (!isSuccessful && isMeasure) {
                onMeasureFailed();
            }
            VoicePlayUtils.getInstance().PlayDisconnect(activity.getMeasureTag());
            tv_device_name.setText(getResources().getText(R.string.disconnect));
            btn_measure.setText(getResources().getText(R.string.connect));
            isMeasure = false;
            hideLoading();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void onMeasureComplete() {
        try {
            VoicePlayUtils.getInstance().PlayMeasureSuccess(activity.getMeasureTag());
            showLoading(getString(R.string.measure_complete));
            BleManager.getInstance().stopNotify(activity.getCurrentDevice(), service_uuid, characteristic_uuid);
            btn_measure.setText(getResources().getText(R.string.measure_complete));
            tv_hp_value.setText(bloodPressure.highPressure + "");
            tv_lp_value.setText(bloodPressure.lowPressure + "");
            tv_pulse_value.setText(bloodPressure.plus + "");
            DataBaseHelper.getInstance(activity).addBloodPressure(bloodPressure);

            if (isAuto) {
                ReportItem item = new ReportItem();
                item.type = DeviceUtils.Category.BLOOD_PRESSURE;
                item.result = "舒张压" + bloodPressure.lowPressure + "\n收缩压" + bloodPressure.highPressure;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                item.time = sdf.format(new Date(bloodPressure.date));
                activity.finishTask(item);
            }

            hideLoading();
            isMeasure = false;
            isSuccessful = true;
            activity.releaseWakeLock();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onMeasureStart() {
        try {
            if (isMeasure || isSuccessful) {
                return;
            }
            VoicePlayUtils.getInstance().PlayMeasureStart(activity.getMeasureTag());
            showLoading(getString(R.string.measuring));
            isMeasure = true;
            btn_measure.setText(getResources().getText(R.string.start_measure));

            activity.wakeLock();
//        activity.sendDeviceData(DeviceUtils.START_MEASURE, service_uuid, characteristic_uuid, new BleWriteCallback() {
//            @Override
//            public void onWriteSuccess(int current, int total, byte[] justWrite) {
//                Log.d("BloodPressureFragment", "发送开始测量成功");
//
//            }
//
//            @Override
//            public void onWriteFailure(BleException exception) {
//                Log.d("BloodPressureFragment", "发送开始测量失败");
//            }
//        });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getCharacteristicHead() {
        return "0000fee1";
    }

    @Override
    void closeNotify() {
        BleManager.getInstance().stopNotify(activity.getCurrentDevice(), service_uuid, characteristic_uuid);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            closeNotify();
            activity.disconnectDevice(activity.getCurrentDevice());
        }
    }
}